package com.burst.reptile.framework.aspectj;

import java.lang.reflect.Method;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.burst.reptile.common.utils.ServletUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.aspectj.lang.annotation.ReadMsg;
import com.burst.reptile.framework.config.SpringContextHolder;
import com.burst.reptile.framework.manager.AsyncManager;
import com.burst.reptile.framework.manager.factory.AsyncFactory;
import com.burst.reptile.framework.security.LoginUser;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.zp.entity.ZpNotice;

import lombok.extern.slf4j.Slf4j;

/**
 * 操作阅读消息处理
 * 
 * @author wujin
 * @date: 2020年5月27日 下午4:05:08
 */
@Aspect
@Component
@Slf4j
public class ReadMsgAspect {
	
	// 配置织入点
	@Pointcut("@annotation(com.burst.reptile.framework.aspectj.lang.annotation.ReadMsg)")
	public void logPointCut() {
	}

	/**
	 * 处理完请求后执行
	 *
	 * @param joinPoint 切点
	 */
	@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
	public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
		handleLog(joinPoint, null, jsonResult);
	}

	/**
	 * 拦截异常操作
	 * 
	 * @param joinPoint 切点
	 * @param e         异常
	 */
	@AfterThrowing(value = "logPointCut()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
		handleLog(joinPoint, e, null);
	}

	protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
		try {
			// 获得注解
			ReadMsg controllerLog = getAnnotationLog(joinPoint);
			if (controllerLog == null) {
				return;
			}
			// 获取当前的用户
			TokenService tokenService = SpringContextHolder.getBean(TokenService.class);
			LoginUser loginUser = tokenService.getWxUser();
			if(ToolUtil.isEmpty(loginUser)) {
				loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
				if(ToolUtil.isEmpty(loginUser)) {
					return;	
				}
			}
			SysUser user = loginUser.getUser();
			if(ToolUtil.isEmpty(user)) {
				return;
			}
			// *========数据库日志=========*//
			// 请求参数
			if(ToolUtil.isNotEmpty(jsonResult)) {
				JSONObject parseObject = JSONObject.parseObject(JSONObject.toJSONString(jsonResult));
				int code = parseObject.getIntValue("code");
				if(code != 0) {
					return;
				}
				JSONArray jsonArray = parseObject.getJSONArray("data");
				List<ZpNotice> javaList = jsonArray.toJavaList(ZpNotice.class);
				if(ToolUtil.isNotEmpty(javaList)) {
					// 保存数据库
					AsyncManager.me().execute(AsyncFactory.recordReadMsg(javaList));
				}
			}
		} catch (Exception exp) {
			// 记录本地异常日志
			log.error("==前置通知异常==");
			log.error("异常信息:{}", exp.getMessage());
			exp.printStackTrace();
		} finally {
		}
	}


	/**
	 * 是否存在注解，如果存在就获取
	 */
	private ReadMsg getAnnotationLog(JoinPoint joinPoint) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(ReadMsg.class);
		}
		return null;
	}

}
